<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>简易Markdown编辑器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            padding: 20px;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }

        .app-container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .main-toolbar {
            padding: 10px 20px;
            background-color: #e9ecef;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .markdown-actions {
            display: flex;
            gap: 8px;
        }

        .tool-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 8px 12px;
            background: none;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #495057;
        }

        .tool-btn:hover {
            background-color: #e9ecef;
            color: #007bff;
        }

        .tool-btn svg {
            width: 20px;
            height: 20px;
            margin-bottom: 4px;
        }

        .shortcut {
            font-size: 10px;
            color: #6c757d;
        }

        .file-actions button {
            padding: 6px 12px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
            margin-left: 5px;
            font-size: 13px;
        }

        .file-actions button:hover {
            background-color: #0056b3;
        }

        .editor-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0;
            /* Remove gap to make it look more integrated */
            height: calc(95vh - 60px);
            /* Adjust height based on toolbar */
        }

        #editor,
        #preview {
            padding: 20px;
            border: none;
            /* Remove individual borders */
            border-radius: 0;
            /* Remove individual border-radius */
            background: white;
            overflow-y: auto;
            /* Ensure vertical scroll */
        }

        #editor {
            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;
            font-size: 15px;
            line-height: 1.7;
            border-right: 1px solid #dee2e6;
            /* Separator line */
            resize: none;
            /* Keep resize none */
        }

        #editor:focus {
            outline: none;
            box-shadow: inset 0 0 0 2px rgba(0, 123, 255, 0.25);
            /* Subtle focus indicator */
        }

        #preview {
            padding: 20px;
            font-size: 15px;
        }

        /* Preview specific styles */
        #preview h1,
        #preview h2,
        #preview h3,
        #preview h4,
        #preview h5,
        #preview h6 {
            margin-top: 1.5em;
            margin-bottom: 0.5em;
            font-weight: 600;
        }

        #preview h1 {
            font-size: 2em;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.3em;
        }

        #preview h2 {
            font-size: 1.75em;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.3em;
        }

        #preview h3 {
            font-size: 1.5em;
        }

        #preview p {
            margin-bottom: 1em;
        }

        #preview ul,
        #preview ol {
            margin-bottom: 1em;
            padding-left: 2em;
        }

        #preview blockquote {
            margin: 1em 0;
            padding: 0.5em 1em;
            border-left: 4px solid #007bff;
            background-color: #f8f9fa;
            color: #555;
        }

        #preview code {
            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;
            background-color: #e9ecef;
            padding: 0.2em 0.4em;
            border-radius: 3px;
            font-size: 0.9em;
        }

        #preview pre {
            background-color: #282c34;
            /* Darker background for code blocks */
            color: #abb2bf;
            /* Lighter text for contrast */
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin-bottom: 1em;
        }

        #preview pre code {
            background-color: transparent;
            /* Reset background for code inside pre */
            padding: 0;
            font-size: 1em;
            /* Reset font size */
            color: inherit;
            /* Inherit color from pre */
        }

        #preview table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 1em;
        }

        #preview th,
        #preview td {
            border: 1px solid #dee2e6;
            padding: 8px 12px;
            text-align: left;
        }

        #preview th {
            background-color: #f1f3f5;
        }

        #preview img {
            max-width: 100%;
            height: auto;
            border-radius: 4px;
        }

        /* Highlight.js style override if needed, or choose a different theme */
        .hljs {
            background: #282c34 !important;
            /* Ensure this matches pre background */
            color: #abb2bf !important;
        }

        /* 帮助模态框样式 */
        .modal {
            display: none;
            /* 默认隐藏 */
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            /* 半透明背景 */
        }

        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            /* 垂直居中，水平自动 */
            padding: 30px;
            border: 1px solid #888;
            width: 60%;
            /* 调整宽度 */
            max-width: 700px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            position: relative;
        }

        .close-btn {
            color: #aaa;
            position: absolute;
            top: 10px;
            right: 20px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close-btn:hover,
        .close-btn:focus {
            color: black;
            text-decoration: none;
        }

        .modal-content h2 {
            margin-top: 0;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .modal-content h3 {
            margin-top: 20px;
            margin-bottom: 10px;
            font-size: 1.2em;
        }

        .modal-content code {
            background-color: #e9ecef;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }

        .modal-content ul {
            list-style: none;
            padding-left: 0;
        }

        .modal-content li {
            margin-bottom: 8px;
        }

        .modal-content kbd {
            /* Style keyboard shortcuts */
            background-color: #eee;
            border-radius: 3px;
            border: 1px solid #b4b4b4;
            box-shadow: 0 1px 1px rgba(0, 0, 0, .2), 0 2px 0 0 rgba(255, 255, 255, .7) inset;
            color: #333;
            display: inline-block;
            font-size: .85em;
            font-weight: 700;
            line-height: 1;
            padding: 2px 4px;
            white-space: nowrap;
        }
    </style>
</head>

<body>
    <div class="app-container">
        <div class="main-toolbar">
            <div class="markdown-actions">
                <div class="tool-btn" id="boldBtn" title="加粗">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M15.6 11.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 7.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z" />
                    </svg>
                    <span class="shortcut">Ctrl+B</span>
                </div>
                <div class="tool-btn" id="italicBtn" title="斜体">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor" d="M10 4v3h2.21l-3.42 8H6v3h8v-3h-2.21l3.42-8H18V4z" />
                    </svg>
                    <span class="shortcut">Ctrl+I</span>
                </div>
                <div class="tool-btn" id="headingBtn" title="标题">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor" d="M5 4v3h5.5v12h3V7H19V4z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+H</span>
                </div>
                <div class="tool-btn" id="ulBtn" title="无序列表">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5zm0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5zM7 19h14v-2H7v2zm0-6h14v-2H7v2zm0-8v2h14V5H7z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+U</span>
                </div>
                <div class="tool-btn" id="olBtn" title="有序列表">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M2 17h2v.5H3v1h1v.5H2v1h3v-4H2v1zm1-9h1V4H2v1h1v3zm-1 3h1.8L2 13.1v.9h3v-1H3.2L5 10.9V10H2v1zm5-6v2h14V5H7zm0 14h14v-2H7v2zm0-6h14v-2H7v2z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+O</span>
                </div>
                <div class="tool-btn" id="checkBtn" title="待办列表">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
                        <path fill="currentColor" d="M10.47 15.27l6.3-6.3-1.41-1.41-4.89 4.89-2.12-2.12-1.41 1.41z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+C</span>
                </div>
                <div class="tool-btn" id="codeBtn" title="代码块">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+K</span>
                </div>
                <div class="tool-btn" id="linkBtn" title="插入链接">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+L</span>
                </div>
                <div class="tool-btn" id="imageBtn" title="插入图片">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor"
                            d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86l-3 3.87L9 13.14 6 17h12l-3.86-5.14z" />
                    </svg>
                    <span class="shortcut">Ctrl+Shift+G</span>
                </div>
            </div>
            <div class="file-actions">
                <button id="helpBtn" title="帮助">?</button>
                <button id="exportBtn" title="导出 Markdown 文件">导出 .md</button>
            </div>
        </div>
        <div class="editor-container">
            <textarea id="editor" placeholder="在此输入Markdown内容..."></textarea>
            <div id="preview"></div>
        </div>
    </div>

    <!-- 帮助模态框 -->
    <div id="helpModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" id="closeHelpModal">&times;</span>
            <h2>Markdown 语法与快捷键帮助</h2>

            <h3>常用 Markdown 语法</h3>
            <ul>
                <li><code># H1</code> / <code>## H2</code> / <code>### H3</code> - 标题</li>
                <li><code>**加粗文字**</code> - 加粗</li>
                <li><code>*斜体文字*</code> - 斜体</li>
                <li><code>- 无序列表项</code> - 无序列表</li>
                <li><code>1. 有序列表项</code> - 有序列表</li>
                <li><code>- [ ] 待办事项</code> / <code>- [x] 已完成</code> - 待办列表</li>
                <li><code>```语言\n代码\n```</code> - 代码块</li>
                <li><code>[链接文字](https://...)</code> - 链接</li>
                <li><code>![图片描述](https://...)</code> - 图片</li>
                <li><code>> 引用文字</code> - 引用</li>
                <li><code>---</code> 或 <code>***</code> - 分隔线</li>
            </ul>

            <h3>快捷键</h3>
            <ul>
                <li>加粗: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>B</kbd></li>
                <li>斜体: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>I</kbd></li>
                <li>标题 (H3): <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>H</kbd></li>
                <li>无序列表: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>U</kbd></li>
                <li>有序列表: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd></li>
                <li>待办列表: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>C</kbd></li>
                <li>代码块: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>K</kbd></li>
                <li>链接: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (输入URL)</li>
                <li>图片: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Shift</kbd> + <kbd>G</kbd> (触发上传) / 粘贴图片</li>
                <li>撤销: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Z</kbd> (浏览器原生)</li>
                <li>重做: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>Y</kbd> (浏览器原生)</li>
                <li>查找: <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + <kbd>F</kbd> (浏览器原生)</li>
            </ul>
        </div>
    </div>

    <!-- Hidden file input for image uploads -->
    <input type="file" id="imageUploadInput" accept="image/*" multiple style="display: none;">

    <!-- 引入依赖库 -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>

    <noscript>
        <style>
            body {
                display: none !important;
            }
        </style>
        <meta http-equiv="refresh" content="0; url=about:blank">
    </noscript>
    <script src="security.js"></script>

    <script>
        // --- 配置项 ---
        const uploadApiUrl = 'https://ask.nbfuli.cn/tool/image/uploadToGithub'; // TODO: 设置你的图片上传接口地址

        $(document).ready(function () {
            // 初始化代码高亮
            hljs.highlightAll();

            // 实时预览功能
            function renderPreview() {
                const markdown = $('#editor').val();
                const html = marked.parse(markdown); // 使用marked.js解析Markdown
                $('#preview').html(html);

                // 重新初始化代码高亮
                $('#preview pre code').each((i, block) => {
                    hljs.highlightBlock(block);
                });
            }

            // 监听输入事件（带防抖）
            let timeout;
            $('#editor').on('input', function () {
                clearTimeout(timeout);
                timeout = setTimeout(renderPreview, 300);
            });

            // 监听回车键事件处理智能列表
            $('#editor').on('keydown', function (e) {
                if (e.key === 'Enter') {
                    const editor = $('#editor')[0];
                    const start = editor.selectionStart;
                    const text = editor.value;
                    const lineStart = text.lastIndexOf('\n', start - 1) + 1;
                    const lineText = text.substring(lineStart, start);

                    // 处理有序列表
                    if (lineText.trim().match(/^\d+\.\s/)) {
                        e.preventDefault();
                        const match = lineText.trim().match(/^(\d+)\./);
                        const nextNum = parseInt(match[1]) + 1;
                        insertText(`\n${nextNum}. `, '', '列表项');
                        return;
                    }

                    // 处理无序列表
                    if (lineText.trim().match(/^[-*+]\s/)) {
                        e.preventDefault();
                        insertText('\n- ', '', '列表项');
                        return;
                    }

                    // 处理空行退出列表
                    if (lineText.trim() === '' &&
                        (text.substring(0, lineStart).trim().match(/^\d+\.\s/) ||
                            text.substring(0, lineStart).trim().match(/^[-*+]\s/))) {
                        e.preventDefault();
                        insertText('\n', '', '');
                        return;
                    }
                }
            });

            // 导出功能
            $('#exportBtn').click(function () {
                const content = $('#editor').val();
                const blob = new Blob([content], { type: 'text/markdown' });
                const url = URL.createObjectURL(blob);

                const a = $('<a>', {
                    href: url,
                    download: 'document.md',
                    style: 'display: none'
                }).appendTo('body');

                a[0].click();
                URL.revokeObjectURL(url);
                a.remove();
            });

            // 初始化Markdown解析器（需要额外引入marked.js）
            // 注意：虽然用户要求只用jQuery和highlight.js，但完整实现需要Markdown解析器
            // 这里通过CDN引入marked.js作为补充
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/marked/marked.min.js';
            script.onload = function () {
                renderPreview(); // 确保marked加载后再渲染一次
            };
            document.head.appendChild(script);

            // --- 辅助函数：在光标处插入文本或包裹选中文本 ---
            function insertText(prefix, suffix = '', placeholder = '文本') {
                const editor = $('#editor')[0];
                const start = editor.selectionStart;
                const end = editor.selectionEnd;
                const text = editor.value;
                const selectedText = text.substring(start, end);

                let newText;
                let newCursorPos;

                if (selectedText) {
                    newText = prefix + selectedText + suffix;
                    editor.value = text.substring(0, start) + newText + text.substring(end);
                    newCursorPos = start + newText.length;
                } else {
                    newText = prefix + placeholder + suffix;
                    editor.value = text.substring(0, start) + newText + text.substring(end);
                    newCursorPos = start + prefix.length;
                    // 选中占位符文本，方便用户直接替换
                    setTimeout(() => { // 需要延迟以确保DOM更新
                        editor.setSelectionRange(newCursorPos, newCursorPos + placeholder.length);
                    }, 0);
                }
                renderPreview();
                editor.focus();
            }

            // --- 工具栏按钮事件 ---
            $('#boldBtn').click(() => insertText('**', '**', '加粗文字'));
            $('#italicBtn').click(() => insertText('*', '*', '斜体文字'));
            $('#headingBtn').click(() => insertText('### ', '', '标题')); // 默认三级标题
            $('#ulBtn').click(() => {
                const editor = $('#editor')[0];
                const start = editor.selectionStart;
                const text = editor.value;
                const lineStart = text.lastIndexOf('\n', start - 1) + 1;
                const lineText = text.substring(lineStart, start);

                // 如果当前行已经是列表项，则插入换行并保持列表格式
                if (lineText.trim().match(/^[-*+]\s/)) {
                    insertText('\n- ', '', '列表项');
                } else if (lineText.trim().match(/^\d+\.\s/)) {
                    insertText('\n- ', '', '列表项');
                } else {
                    insertText('- ', '', '列表项');
                }
            });
            $('#olBtn').click(() => {
                const editor = $('#editor')[0];
                const start = editor.selectionStart;
                const text = editor.value;
                const lineStart = text.lastIndexOf('\n', start - 1) + 1;
                const lineText = text.substring(lineStart, start);

                // 如果当前行已经是有序列表项，则插入换行并递增编号
                if (lineText.trim().match(/^\d+\.\s/)) {
                    const match = lineText.trim().match(/^(\d+)\./);
                    const nextNum = parseInt(match[1]) + 1;
                    insertText(`\n${nextNum}. `, '', '列表项');
                } else if (lineText.trim().match(/^[-*+]\s/)) {
                    insertText('\n1. ', '', '列表项');
                } else {
                    insertText('1. ', '', '列表项');
                }
            });
            $('#checkBtn').click(() => insertText('- [ ] ', '', '待办事项'));
            $('#codeBtn').click(() => insertText('\n```\n', '\n```\n', '代码'));
            $('#linkBtn').click(() => {
                const url = prompt("请输入链接URL:", "https://");
                if (url) {
                    insertText('[', `](${url})`, '链接文字');
                }
            });
            // 修改图片按钮：触发文件选择
            $('#imageBtn').click(() => {
                $('#imageUploadInput').click(); // 触发隐藏的文件输入
            });

            // --- 快捷键处理 ---
            $('#editor').keydown(function (e) {
                const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
                const ctrlKey = isMac ? e.metaKey : e.ctrlKey; // Command for Mac, Ctrl for Win/Linux

                if (ctrlKey) {
                    switch (e.key.toUpperCase()) {
                        case 'B': // 加粗
                            e.preventDefault();
                            insertText('**', '**', '加粗文字');
                            break;
                        case 'I': // 斜体
                            e.preventDefault();
                            insertText('*', '*', '斜体文字');
                            break;
                        case 'G': // 替换 (Ctrl+G), 插入图片 (Ctrl+Shift+G)
                            if (e.shiftKey) { // 插入图片 - 修改为触发上传
                                e.preventDefault();
                                $('#imageUploadInput').click(); // 触发隐藏的文件输入
                            } else {
                                // 替换功能通常需要更复杂的UI，这里仅作占位
                                // alert('替换功能 (Ctrl+G) 待实现');
                            }
                            break;
                        case 'F': // 查找
                            // 浏览器默认查找
                            break;
                    }

                    if (e.shiftKey) {
                        switch (e.key.toUpperCase()) {
                            case 'H': // 标题
                                e.preventDefault();
                                insertText('### ', '', '标题');
                                break;
                            case 'O': // 有序列表
                                e.preventDefault();
                                const olEditor = $('#editor')[0];
                                const olStart = olEditor.selectionStart;
                                const olText = olEditor.value;
                                const olLineStart = olText.lastIndexOf('\n', olStart - 1) + 1;
                                const olLineText = olText.substring(olLineStart, olStart);

                                // 如果当前行已经是有序列表项，则插入换行并递增编号
                                if (olLineText.trim().match(/^\d+\.\s/)) {
                                    const match = olLineText.trim().match(/^(\d+)\./);
                                    const nextNum = parseInt(match[1]) + 1;
                                    insertText(`\n${nextNum}. `, '', '列表项');
                                } else if (olLineText.trim().match(/^[-*+]\s/)) {
                                    insertText('\n1. ', '', '列表项');
                                } else {
                                    insertText('1. ', '', '列表项');
                                }
                                break;
                            case 'U': // 无序列表
                                e.preventDefault();
                                const ulEditor = $('#editor')[0];
                                const ulStart = ulEditor.selectionStart;
                                const ulText = ulEditor.value;
                                const ulLineStart = ulText.lastIndexOf('\n', ulStart - 1) + 1;
                                const ulLineText = ulText.substring(ulLineStart, ulStart);

                                // 如果当前行已经是列表项，则插入换行并保持列表格式
                                if (ulLineText.trim().match(/^[-*+]\s/)) {
                                    insertText('\n- ', '', '列表项');
                                } else if (ulLineText.trim().match(/^\d+\.\s/)) {
                                    insertText('\n- ', '', '列表项');
                                } else {
                                    insertText('- ', '', '列表项');
                                }
                                break;
                            case 'C': // 待办列表
                                e.preventDefault();
                                insertText('- [ ] ', '', '待办事项');
                                break;
                            case 'K': // 插入代码
                                e.preventDefault();
                                insertText('\n```\n', '\n```\n', '代码');
                                break;
                            case 'L': // 插入链接
                                e.preventDefault();
                                const url = prompt("请输入链接URL:", "https://");
                                if (url) {
                                    insertText('[', `](${url})`, '链接文字');
                                }
                                break;
                        }
                    }
                }
                // 撤销 (Ctrl+Z) 和 重做 (Ctrl+Y) 通常由浏览器或操作系统处理文本区域的输入
                // 如果需要自定义实现，会更复杂，涉及到历史记录管理
            });

            // --- 图片上传逻辑 ---
            $('#imageUploadInput').on('change', function (event) {
                const files = event.target.files;
                if (files.length > 0) {
                    for (let i = 0; i < files.length; i++) {
                        uploadImage(files[i]);
                    }
                    // 清空input的值，以便下次选择相同文件也能触发change事件
                    $(this).val('');
                }
            });

            // --- 粘贴图片上传 ---
            $('#editor').on('paste', function (event) {
                const items = (event.clipboardData || event.originalEvent.clipboardData).items;
                let hasImage = false;
                for (let index in items) {
                    const item = items[index];
                    if (item.kind === 'file' && item.type.startsWith('image/')) {
                        const blob = item.getAsFile();
                        uploadImage(blob);
                        hasImage = true;
                    }
                }
                if (hasImage) {
                    event.preventDefault(); // 阻止默认的粘贴行为（如果粘贴的是图片）
                }
            });

            // --- 帮助模态框逻辑 ---
            $('#helpBtn').click(function () {
                $('#helpModal').show();
            });

            $('#closeHelpModal').click(function () {
                $('#helpModal').hide();
            });

            // 点击模态框外部区域关闭
            $(window).click(function (event) {
                if (event.target === $('#helpModal')[0]) {
                    $('#helpModal').hide();
                }
            });

            // 按ESC关闭模态框
            $(document).keydown(function (event) {
                if (event.key === "Escape" && $('#helpModal').is(':visible')) {
                    $('#helpModal').hide();
                }
            });

            // --- 上传函数 ---
            function uploadImage(file) {
                const formData = new FormData();
                formData.append('files[]', file); // 'image' 是后端接收文件的字段名，可以根据需要修改

                // 显示上传中的提示
                const placeholderText = `![上传中 ${file.name}...]()`;
                const currentEditorValue = $('#editor').val();
                $('#editor').val(currentEditorValue + '\n' + placeholderText);
                renderPreview();

                $.ajax({
                    url: uploadApiUrl,
                    type: 'POST',
                    data: formData,
                    processData: false, // 告诉jQuery不要处理发送的数据
                    contentType: false, // 告诉jQuery不要设置contentType
                    success: function (response) {
                        // 假设后端返回 { success: true, url: '...' } 或 { success: false, message: '...' }
                        if (response && response.success && response.url) {
                            const markdownImage = `![${file.name}](${response.url})`;
                            // 替换掉上传中的占位符
                            const currentContent = $('#editor').val();
                            const updatedEditorValue = currentContent.replace(placeholderText, markdownImage);
                            $('#editor').val(updatedEditorValue);
                            renderPreview();
                        } else {
                            const errorMessage = response && response.message ? response.message : '上传失败';
                            alert(`图片上传失败: ${errorMessage}`);
                            // 移除上传中的占位符
                            const currentContent = $('#editor').val();
                            const updatedEditorValue = currentContent.replace(placeholderText, `![上传失败: ${file.name}]()`);
                            $('#editor').val(updatedEditorValue);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(`图片上传请求失败: ${textStatus} - ${errorThrown}`);
                        // 移除上传中的占位符
                        const updatedEditorValue = currentEditorValue.replace(placeholderText, `![上传失败: ${file.name}]()`);
                        $('#editor').val(updatedEditorValue);
                    },
                    complete: function () {
                        // 可选：隐藏上传中的提示
                        $('#editor')[0].focus(); // 将焦点移回编辑器
                    }
                });
            }

        });
    </script>
</body>

</html>